// 模拟手机控制测试
const WebSocket = require('ws');

console.log('========================================');
console.log('模拟手机控制测试');
console.log('========================================\n');

console.log('连接到服务器...');
const ws = new WebSocket('ws://localhost:7664');

ws.on('open', () => {
  console.log('✓ 连接成功\n');
  
  // 发送连接消息
  console.log('发送连接消息...');
  ws.send(JSON.stringify({
    type: 'connect',
    clientId: 'test-mobile-' + Date.now()
  }));
  
  // 等待3秒后开始发送控制指令
  setTimeout(() => {
    console.log('\n开始发送控制指令...');
    console.log('请确保PowerPoint已打开并在前台\n');
    
    let count = 0;
    const interval = setInterval(() => {
      count++;
      const action = count % 2 === 1 ? 'next' : 'previous';
      const actionName = action === 'next' ? '下一页' : '上一页';
      
      console.log(`发送指令 ${count}: ${actionName}`);
      ws.send(JSON.stringify({
        type: 'control',
        action: action,
        timestamp: Date.now()
      }));
      
      if (count >= 6) {
        clearInterval(interval);
        setTimeout(() => {
          console.log('\n测试完成，关闭连接');
          ws.close();
        }, 2000);
      }
    }, 3000);
  }, 3000);
});

ws.on('message', (data) => {
  try {
    const message = JSON.parse(data);
    console.log(`收到服务器消息: ${message.type}`);
    
    if (message.type === 'connected') {
      console.log('  ✓ 服务器确认连接');
    } else if (message.type === 'slideUpdate') {
      console.log(`  ✓ 幻灯片更新 - 页码: ${message.slideIndex}`);
    } else if (message.type === 'error') {
      console.log(`  ✗ 错误: ${message.message}`);
    }
  } catch (error) {
    console.log('解析消息失败:', error.message);
  }
});

ws.on('error', (error) => {
  console.log('✗ WebSocket错误:', error.message);
  process.exit(1);
});

ws.on('close', () => {
  console.log('\nWebSocket连接已关闭');
  process.exit(0);
});

// 超时保护
setTimeout(() => {
  console.log('\n测试超时');
  ws.close();
  process.exit(1);
}, 30000);